import os
import re
import traceback

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
# from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.support.ui import WebDriverWait


def path_create(dir_path):
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)


def download_m3u8_video(url, file_path):
    r = requests.get(url)
    if r.status_code != 200:
        print('m3u8视频下载链接无效')
        return False

    m3u8_list = r.text.split('\n')
    m3u8_list = [i for i in m3u8_list if i and i[0] != '#']

    ts_list = []
    for ts_url in m3u8_list:
        ts_url = url.rsplit('/', 1)[0] + '/' + ts_url
        ts_list.append(ts_url)

    with open(file_path, 'wb') as f:
        for ts_url in ts_list:
            r = requests.get(ts_url)
            if r.status_code == 200:
                f.write(r.content)
    print('m3u8视频下载完成')
    return True


def convert_ts_to_mp4(ts_file_path, mp4_file_path):
    os.system(f'ffmpeg -i {ts_file_path} -c copy {mp4_file_path}')


def get_html_by_selenium(url: str, timeout=10) -> str:
    driver = webdriver.Chrome()

    # driver = webdriver.Remote(
    #     # 指定远程浏览器的地址
    #     command_executor=SELENIUM_SERVER_URL,
    #     # 指定期望的浏览器类型，这里安装的是 firefox 所以指定firefox
    #     desired_capabilities=DesiredCapabilities.FIREFOX,
    # )
    # 等待
    def document_loaded(driver_):
        return driver_.execute_script("")

    content = ""
    try:
        # 打开网页
        driver.get(url)
        # 等待页面加载完成
        try:
            WebDriverWait(driver, timeout=timeout).until(document_loaded)
        except:
            pass
        # 提取需要的内容
        content = driver.page_source
    except Exception as e:
        print(str(e))
        traceback.print_exc()
    return content


def analysis_youtube_page_source_video_ids(html_: str) -> list:
    soup = BeautifulSoup(html_, 'html.parser')
    tags = soup.select("a")
    a_list = []
    for item in tags:
        href = item.get("href")
        if re.search(r"/watch\?v=.+", str(href), flags=re.I):
            a_list.append(href)
    video_ids = []
    for item in a_list:
        search = re.search(r"(?<=/watch\?v=)[a-zA-Z0-9_-]+", str(item), flags=re.I)
        if search:
            video_ids.append(search.group())
    return list(set(video_ids))
